package com.lavida.project.system.attendance.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.ibatis.annotations.Update;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ResourceProperties.Content;
import org.springframework.stereotype.Service;

import com.github.pagehelper.util.StringUtil;
import com.lavida.common.utils.DateUtils;
import com.lavida.common.utils.ExcelReaderutil;
import com.lavida.project.system.attendance.domain.Attendances;
import com.lavida.project.system.attendance.domain.Attendancess;
import com.lavida.project.system.attendance.mapper.AttendanceMapper;
import com.lavida.project.system.attendance.mapper.AttendancessMapper;



@Service
public class AttendancessServiceimpl implements AttendancessService{

	@Autowired
	private AttendancessMapper attendancessMapper;
	
	@Autowired
    private static Logger logger = Logger.getLogger(AttendancessServiceimpl.class.getName()); // 日志打印类

    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";
	
	@Override
	public long insertAttendancessm(String fileName) throws Exception{
		List<Attendancess> parsedResult = readExcel(fileName);
		System.out.println(fileName);
		System.out.println(parsedResult.toString());
		long number =0;
		for(Attendancess attendancess : parsedResult) {
			attendancessMapper.insertAttendancessm(attendancess);
			System.out.println(number);
			number = number++;
		}
		System.out.println(number);
		return number;
	}
	/**
     * 根据文件后缀名类型获取对应的工作簿对象
     * @param inputStream 读取文件的输入流
     * @param fileType 文件后缀名类型（xls或xlsx）
     * @return 包含文件数据的工作簿对象
     * @throws IOException
     */
    public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
        Workbook workbook = null;
        if (fileType.equals(XLS)) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileType.equals(XLSX)) {
            workbook = new XSSFWorkbook(inputStream);
        }
        return workbook;
    }

    /**
     * 读取Excel文件内容
     * @param fileName 要读取的Excel文件所在路径
     * @return 读取结果列表，读取失败时返回null
     */
    public static List<Attendancess> readExcel(String fileName) {

        Workbook workbook = null;
        FileInputStream inputStream = null;

        try {
            // 获取Excel后缀名
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            // 获取Excel文件
            File excelFile = new File(fileName);
            if (!excelFile.exists()) {
                logger.warn("指定的Excel文件不存在！");
                return null;
            }

            // 获取Excel工作簿
            inputStream = new FileInputStream(excelFile);
            workbook = getWorkbook(inputStream, fileType);

            // 读取excel中的数据
            List<Attendancess> resultDataList = parseExcel(workbook);

            return resultDataList;
        } catch (Exception e) {
            System.out.println(("解析Excel失败，文件名：" + fileName + " 错误信息：" + e.getMessage()));
            return null;
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                System.out.println("关闭数据流出错！错误信息：" + e.getMessage());
                return null;
            }
        }
    }

    /**
     * 解析Excel数据
     * @param workbook Excel工作簿对象
     * @return 解析结果
     */
    private static List<Attendancess> parseExcel(Workbook workbook) {
       List<Attendancess> resultDataList = new ArrayList<>();
       workbook.getNumberOfSheets();
        // 解析sheet
        for (int sheetNum = 0; sheetNum <workbook.getNumberOfSheets(); sheetNum++) {
            Sheet sheet = workbook.getSheetAt(sheetNum);
            // 校验sheet是否合法
            if (sheet == null ) {
                continue;
            }

            // 获取第一行数据
            int firstRowNum = sheet.getFirstRowNum();
            Row firstRow = sheet.getRow(firstRowNum);
            String firstTime = "";
            if (null == firstRow) {
                logger.warn("解析Excel失败，在第一行没有读取到任何数据！");
            }/*else {
            	System.out.println("+++++++++++++++++++++++++++"+firstRow.toString());
            	Cell fCell = firstRow.getCell(0);
            	String times = fCell.getStringCellValue();
            	Pattern pattern = Pattern.compile("[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}");
        	    Matcher matcher = pattern.matcher(times);
        	    String dateStr = null;
        	    if(matcher.find()){
        	      dateStr = matcher.group(0);
        	    }
        	    
        	    firstTime =dateStr.toString();
            }*/
            System.out.println("-------------------------"+firstTime);
            // 解析每一行的数据，构造数据对象
            int rowStart = firstRowNum + 1;
            int rowEnd = sheet.getPhysicalNumberOfRows();
            for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (null == row) {
                    continue;
                }

                Attendancess resultData = convertRowToData(row);
                if (null == resultData) {
                    logger.warn("第 " + row.getRowNum() + "行数据不合法，已忽略！");
                    continue;
                }
                resultDataList.add(resultData);
            }
        }

        return resultDataList;
    }

    /**
     * 将单元格内容转换为字符串
     * @param cell
     * @return
     */
    private static String convertCellValueToString(Cell cell) {
        if(cell==null){
            return null;
        }
        String returnValue = null;
        switch (cell.getCellTypeEnum()) {
            case NUMERIC:   //数字
                Double doubleValue = cell.getNumericCellValue();
                // 格式化科学计数法，取一位整数
                DecimalFormat df = new DecimalFormat("0");
                returnValue = df.format(doubleValue);
                break;
            case STRING:    //字符串
                returnValue = cell.getStringCellValue();
                break;
            case BOOLEAN:   //布尔
                Boolean booleanValue = cell.getBooleanCellValue();
                returnValue = booleanValue.toString();
                break;
            case BLANK:     // 空值
                break;
            case FORMULA:   // 公式
                returnValue = cell.getCellFormula();
                break;
            case ERROR:     // 故障
                break;
            default:
                break;
        }
        return returnValue;
    }
   
    /**
     * 提取每一行中需要的数据，构造成为一个结果数据对象
     *
     * 当该行中有单元格的数据为空或不合法时，忽略该行的数据
     *
     * @param row 行数据
     * @return 解析后的行数据对象，行数据错误时返回null
     */
    private static Attendancess convertRowToData(Row row) {
       Attendancess resultData = new Attendancess();
       try {
	       Cell cell;
	       int cellNum = 0;
	       //获取工号
	       cell = row.getCell(cellNum++);
	       String job_id = convertCellValueToString(cell);
	       System.out.println(job_id+"    ");
	       if (null == job_id || "".equals(job_id)) {
	           resultData.setJob_id(0);
	       } else {
	           resultData.setJob_id(0);
	       }
	       //获取姓名
	       cell = row.getCell(cellNum++);
	       String names = convertCellValueToString(cell);
	       System.out.println(names+"    ");
	       if (null == names || "".equals(names)) {
	           resultData.setNames("未填");
	       } else {
	           resultData.setNames(names);
	       }
	       //获取日期
	       cell = row.getCell(cellNum++);
	       Date date = cell.getDateCellValue();
	       System.out.println("获取日期："+date+"    ");
	       //时间
		   if (null == date || "".equals(date)) {
		    	Date date1 = DateUtils.parseDate("1890/12/05");
		    	resultData.setDates(date1);
		    	resultData.setYear(DateUtils.dateYear(date1));
		    	resultData.setMonth(DateUtils.dateMonth(date1));
		    }else {	
		    	String date2 = DateUtils.parseDateToStr("yyyy-MM-dd", date);
		    	Date dates = DateUtils.parseDate(date2);
		    	System.out.println(dates.toString());
		    	resultData.setDates(dates);
		    	resultData.setYear(DateUtils.dateYear(dates));
		    	resultData.setMonth(DateUtils.dateMonth(dates));
		    }
	       //获取部门
	       cell = row.getCell(cellNum++);
	       String dept = convertCellValueToString(cell);
	       System.out.println(dept+"    ");
	       if (null == dept || "".equals(dept)) {
	           resultData.setDept("暂无");
	       } else {
	           resultData.setDept(dept);
	       }
	       //获取迟到次数
	       cell = row.getCell(cellNum++);
	       String latenumber = convertCellValueToString(cell);
	       System.out.println(latenumber+"    ");
	       if (null == latenumber || "".equals(latenumber)) {
	           resultData.setLatenumber(0.0);
	       } else {
	           resultData.setLatenumber(Double.valueOf(latenumber));
	       }
	       //获取严重迟到次数
	       cell = row.getCell(cellNum++);
	       String serouslatenumber = convertCellValueToString(cell);
	       System.out.println(serouslatenumber+"    ");
	       if (null == serouslatenumber || "".equals(serouslatenumber)) {
	           resultData.setSerouslatenumber(0.0);
	       } else {
	           resultData.setSerouslatenumber(Double.valueOf(serouslatenumber));
	       }
	       //获取迟到时长
	       cell = row.getCell(cellNum++);
	       String latetime = convertCellValueToString(cell);
	       System.out.println(latetime+"    ");
	       if (null == latetime || "".equals(latetime)) {
	           resultData.setLatetime(0.0);
	       } else {
	           resultData.setLatetime(Double.valueOf(latetime));
	       }
	       //获取早退次数
	       cell = row.getCell(cellNum++);
	       String earlynumber = convertCellValueToString(cell);
	       System.out.println(earlynumber+"    ");
	       if (null == earlynumber || "".equals(earlynumber)) {
	           resultData.setEarlynumber(0.0);
	       } else {
	           resultData.setEarlynumber(Double.valueOf(earlynumber));
	       }
	       //获取严重早退次数
	       cell = row.getCell(cellNum++);
	       String seearlynumber = convertCellValueToString(cell);
	       System.out.println(seearlynumber+"    ");
	       if (null == seearlynumber || "".equals(seearlynumber)) {
	           resultData.setSeearlynumber(0.0);
	       } else {
	           resultData.setSeearlynumber(Double.valueOf(seearlynumber));
	       }
	       //获取严重早退时长
	       cell = row.getCell(cellNum++);
	       String earlytime = convertCellValueToString(cell);
	       System.out.println(earlytime+"    ");
	       if (null == earlytime || "".equals(earlytime)) {
	           resultData.setEarlytime(0.0);
	       } else {
	           resultData.setEarlytime(Double.valueOf(earlytime));
	       }
	       //获取旷工时长
	       cell = row.getCell(cellNum++);
	       String kgtime = convertCellValueToString(cell);
	       System.out.println(kgtime+"    ");
	       if (null == kgtime || "".equals(kgtime)) {
	           resultData.setKgtime(0.0);
	       } else {
	           resultData.setKgtime(Double.valueOf(kgtime));
	       }
	       //获取年假
	       cell = row.getCell(cellNum++);
	       String review = convertCellValueToString(cell);
	       System.out.println(review+"    ");
	       if (null == review || "".equals(review)) {
	           resultData.setReview(0.0);
	       } else {
	           resultData.setReview(Double.valueOf(review));
	       }
	       //获取换休
	       cell = row.getCell(cellNum++);
	       String huanxiu = convertCellValueToString(cell);
	       System.out.println(huanxiu+"    ");
	       if (null == huanxiu || "".equals(huanxiu)) {
	           resultData.setHuanxiu(0.0);
	       } else {
	           resultData.setHuanxiu(Double.valueOf(huanxiu));
	       }
	       //获取事假
	       cell = row.getCell(cellNum++);
	       String shijia = convertCellValueToString(cell);
	       System.out.println(shijia+"    ");
	       if (null == shijia || "".equals(shijia)) {
	           resultData.setShijia(0.0);
	       } else {
	           resultData.setShijia(Double.valueOf(shijia));
	       }
	       //获取病假
	       cell = row.getCell(cellNum++);
	       String sick = convertCellValueToString(cell);
	       System.out.println(sick+"    ");
	       if (null == sick || "".equals(sick)) {
	           resultData.setSick(0.0);
	       } else {
	           resultData.setSick(Double.valueOf(sick));
	       }
	       //获取产假/产检假
	       cell = row.getCell(cellNum++);
	       String ccjia = convertCellValueToString(cell);
	       System.out.println(ccjia+"    ");
	       if (null == ccjia || "".equals(ccjia)) {
	           resultData.setCcjia(0.00);
	       } else {
	           resultData.setCcjia(Double.valueOf(ccjia));
	       }
	       //获取工作日加班
	       cell = row.getCell(cellNum++);
	       String workg = convertCellValueToString(cell);
	       System.out.println(workg+"    ");
	       if (null == workg || "".equals(workg)) {
	           resultData.setWorkg(0.00);
	       } else {
	           resultData.setWorkg(Double.valueOf(workg));
	       }
	       //获取休息日加班
	       cell = row.getCell(cellNum++);
	       String workx = convertCellValueToString(cell);
	       System.out.println(workx+"    ");
	       if (null == workx || "".equals(workx)) {
	           resultData.setWorkx(0.00);
	       } else {
	           resultData.setWorkx(Double.valueOf(workx));
	       }
	       //获取节假日加班
	       cell = row.getCell(cellNum++);
	       String workj = convertCellValueToString(cell);
	       System.out.println(workj+"    ");
	       if (null == workj || "".equals(workj)) {
	           resultData.setWorkj(0.00);
	       } else {
	           resultData.setWorkj(Double.valueOf(workj));
	       }
		   
       	}catch (Exception e) {
   		// TODO: handle exception
       		e.printStackTrace();
       	}
	    return resultData;
    }
	@Override
	public long insertAttendancessms(String filePath) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}
	@Override
	public long updateAttendancessm(Attendancess attendancess) {
		// TODO Auto-generated method stub
		return attendancessMapper.updateAttendancessm(attendancess);
	}
	@Override
	public Attendancess AttendancessById(String job_id) {
		// TODO Auto-generated method stub
		return attendancessMapper.AttendancessById(job_id);
	}
	@Override
	public Attendancess AttendancessmById(Integer job_id) {
		// TODO Auto-generated method stub
		return attendancessMapper.AttendancessmById(job_id);
	}
	@Override
	public List<Attendancess> selectAttendancessm(Attendancess attendencess, String fromtime, String totime) {
		// TODO Auto-generated method stub
		List<Attendancess> attendancesses = attendancessMapper.selectAttendancessm(attendencess, fromtime, totime);
		return attendancesses;
	}

	
}